import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bigegg/common/log/xmm_logcat.dart';
import 'package:bigegg/common/sp/xmm_shared_preferences_util.dart';
import 'package:bigegg/data/repository/xmm_remote_repository.dart';
import 'package:bigegg/entity/im/xmm_im_message.dart';
import 'package:bigegg/global/im/xmm_im_manager.dart';
import 'package:bigegg/global/xmm_app_const.dart';
import 'package:bigegg/page/im/preview/xmm_media_preview_page.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:svgaplayer_flutter/player.dart';

import '../../../../entity/user/xmm_wall_user.dart';
import '../../../../global/user/xmm_account_manager.dart';
import '../../../../widget/image/xmm_circle_cached_network_image.dart';
import '../xmm_chat_controller.dart';

class XmmMessageItem extends StatefulWidget {
  const XmmMessageItem(this.messageWarp, this.user, {super.key});

  final XmmImMessageWarp messageWarp;

  final XmmWallUser user;

  @override
  State<StatefulWidget> createState() {
    return XmmMessageItemState();
  }
}

class XmmMessageItemState extends State<XmmMessageItem> {
  final XmmChatController controller = Get.find<XmmChatController>();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  bool isSend() {
    return widget.messageWarp.message.direction == RCIMIWMessageDirection.send;
  }

  bool isReceive() {
    return widget.messageWarp.message.direction ==
        RCIMIWMessageDirection.receive;
  }

  void clickMessage() {
    var message = widget.messageWarp.message;
    if (message is RCIMIWImageMessage) {
      Get.to(() => XmmMediaPreviewPage(user: widget.user, message: message));
    } else if (message is RCIMIWVoiceMessage) {
      String? path;
      if (message.local != null && File(message.local!).existsSync()) {
        path = message.local;
      } else {
        path = message.remote;
        XmmImManager.instance.engine?.downloadMediaMessage(message);
      }
      if (path != null && path.isNotEmpty) {
        controller.startPlayAudio(path, onProgress: (duration, position) {
          var progress = duration.inSeconds - position.inSeconds;
          if (progress <= 0) return;
          if (message.extra == null ||
              progress < (int.tryParse(message.extra!) ?? 0)) {
            message.extra = "$progress";
            setState(() {});
          }
        }, onFinished: () {
          message.extra = null;
          setState(() {});
        });
      }
    } else if (message is RCIMIWFileMessage) {
      Get.to(() => XmmMediaPreviewPage(user: widget.user, message: message));
    } else {}
  }

  @override
  Widget build(BuildContext context) {
    return itemWidget();
  }

  Widget itemWidget() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      textDirection: isSend() ? TextDirection.rtl : TextDirection.ltr,
      children: [
        const SizedBox(width: 19),
        avatarWidget(),
        const SizedBox(width: 10),
        Container(
          margin: const EdgeInsets.only(top: 10),
          child: Row(
            textDirection: isSend() ? TextDirection.rtl : TextDirection.ltr,
            children: [
              itemContentWidget(),
              translateWidget(),
              sendStatusWidget()
            ],
          ),
        )
      ],
    );
  }

  Widget avatarWidget() {
    return XmmCircleCachedNetworkImage(
      imageUrl: isSend()
          ? XmmAccountManager.instance.user.avatarUrl ?? ""
          : widget.user.getAvatarUrl ?? "",
      height: 44,
      width: 44,
    );
  }

  Widget sendStatusWidget() {
    return Obx(() {
      XmmXLogcat.i(
          "send status widget ${widget.messageWarp.messageStatus.value}");
      final Widget view;
      if (isSend()) {
        if (widget.messageWarp.message.sentStatus == RCIMIWSentStatus.failed) {
          view = GestureDetector(
            onTap: () => controller.sendMessage(widget.messageWarp.message),
            child: Container(
              width: 20,
              height: 20,
              margin: const EdgeInsets.only(right: 8),
              child: Image.asset("assets/images/xmm_icon_send_warning.png"),
            ),
          );
        } else if (widget.messageWarp.message.sentStatus ==
            RCIMIWSentStatus.sending) {
          view = Container(
            width: 20,
            height: 20,
            margin: const EdgeInsets.only(right: 8),
            child: const CircularProgressIndicator(
              value: null,
              color: Colors.blue,
              strokeWidth: 3,
            ),
          );
        } else {
          view = Container();
        }
      } else {
        view = Container();
      }
      return view;
    });
  }

  Widget translateWidget() {
    if (isReceive() && widget.messageWarp.message is RCIMIWTextMessage) {
      void translate() async {
        if (widget.messageWarp.message.extra?.isNotEmpty == true)
          return; //存在翻译数据不再请求
        var text = (widget.messageWarp.message as RCIMIWTextMessage).text ?? "";
        String? txt = await XmmRemoteRepository().translate(text);
        widget.messageWarp.message.extra = txt;
        setState(() {});
      }

      if (XmmSPUtil.get(XmmAppConst.spAutoTranslateKey, defValue: false)) {
        translate();
      }
      return GestureDetector(
        onTap: () => translate(),
        child: Container(
          alignment: Alignment.center,
          height: 16,
          width: 16,
          margin: const EdgeInsets.only(left: 8),
          child: Image.asset('assets/images/xmm_icon_message_translate.png'),
        ),
      );
    }
    return Container();
  }

  Widget itemContentWidget() {
    var message = widget.messageWarp.message;
    Widget view;
    if (message is RCIMIWTextMessage) {
      view = textMessageWidget();
    } else if (message is RCIMIWImageMessage) {
      view = imageMessageWidget();
    } else if (message is RCIMIWVoiceMessage) {
      view = voiceMessageWidget();
    } else if (message is RCIMIWFileMessage) {
      view = fileMessageWidget();
    } else {
      view = Container();
    }
    return GestureDetector(
      onTap: () => clickMessage(),
      child: Container(child: view),
    );
  }

  Widget fileMessageWidget() {
    var message = widget.messageWarp.message as RCIMIWFileMessage;
    return Container(
      color: Color(isSend() ? 0xFF15E8C2 : 0xFFEEEEEE),
      padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
      child: Row(
        children: [
          Text(
            "Please check my file",
            style: TextStyle(
              color: isSend() ? Colors.white : const Color(0xFF202020),
              fontSize: 14,
            ),
          ),
          const SizedBox(width: 7),
          Image.asset(
            "assets/images/xmm_icon_message_file.png",
            height: 24,
            width: 24,
          )
        ],
      ),
    );
  }

  Widget voiceMessageWidget() {
    var message = widget.messageWarp.message as RCIMIWVoiceMessage;
    Widget voiceIconWidget = Container();
    if (isSend()) {
      if (message.extra != null) {
        voiceIconWidget = const SizedBox(
          width: 19,
          height: 19,
          child: SVGASimpleImage(
            assetsName: 'assets/images/svga/xmm_voice_play_in_send.svga',
          ),
        );
      } else {
        voiceIconWidget = Image.asset(
          "assets/images/xmm_icon_send_voice.png",
          width: 19,
          height: 19,
        );
      }
    } else {
      if (message.extra != null) {
        voiceIconWidget = const SizedBox(
          width: 19,
          height: 19,
          child: SVGASimpleImage(
            assetsName: 'assets/images/svga/xmm_voice_play_in_received.svga',
          ),
        );
      } else {
        voiceIconWidget = Image.asset(
          "assets/images/xmm_icon_receive_voice.png",
          width: 19,
          height: 19,
        );
      }
    }
    return Container(
      color: Color(isSend() ? 0xFF15E8C2 : 0xFFEEEEEE),
      constraints: const BoxConstraints(maxWidth: 179, minWidth: 70),
      padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        textDirection: isSend() ? TextDirection.rtl : TextDirection.ltr,
        children: [
          voiceIconWidget,
          const SizedBox(width: 10),
          Text(
            "${message.extra ?? message.duration}“",
            style: TextStyle(
              fontSize: 16,
              color: isSend() ? Colors.white : const Color(0xFF202020),
            ),
          ),
          Visibility(
            visible: !isSend() &&
                message.receivedStatus == RCIMIWReceivedStatus.listened,
            child: Container(
              margin: const EdgeInsets.only(left: 15),
              height: 8,
              width: 8,
              decoration: const BoxDecoration(
                  shape: BoxShape.circle, color: Colors.red),
            ),
          )
        ],
      ),
    );
  }

  Widget imageMessageWidget() {
    var message = widget.messageWarp.message as RCIMIWImageMessage;
    if (message.thumbnailBase64String != null) {
      Uint8List bytes = base64.decode(message.thumbnailBase64String!);
      return ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Image.memory(bytes, fit: BoxFit.cover),
      );
    } else if (message.local != null &&
        File(message.local ?? "").existsSync()) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Image.file(File(message.local ?? ""), fit: BoxFit.cover),
      );
    } else {
      return CachedNetworkImage(
        progressIndicatorBuilder: (context, url, progress) =>
            CircularProgressIndicator(
          value: progress.progress,
        ),
        imageBuilder: (context, imageProvider) => Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            image: DecorationImage(image: imageProvider, fit: BoxFit.cover),
          ),
        ),
        imageUrl: message.remote ?? "",
      );
    }
  }

  Widget textMessageWidget() {
    var message = widget.messageWarp.message as RCIMIWTextMessage;
    var isRight = isSend();
    return Container(
      color: Color(isSend() ? 0xFF15E8C2 : 0xFFEEEEEE),
      constraints: BoxConstraints(maxWidth: 179),
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 14),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            message.text ?? "",
            style: TextStyle(
              color: isRight ? Colors.white : const Color(0xFF202020),
              fontSize: 14.sp,
            ),
          ),
          Visibility(
            visible: message.extra?.isNotEmpty == true,
            child: Container(
              margin: const EdgeInsets.only(top: 12),
              padding: const EdgeInsets.only(top: 12),
              decoration: const BoxDecoration(
                border: Border(
                  top: BorderSide(
                    color: Color(0xFFCCCCCC), // Set the color of the border
                    width: 0.5, // Set the width of the border
                  ),
                ),
              ),
              child: Text(
                message.extra ?? "",
                style: TextStyle(
                  color: isRight ? Colors.white : const Color(0xFF202020),
                  fontSize: 14.sp,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
